<template>
  <div id="app">
    <div class="todo-container">
      <div class="todo-header">
        <input type="text" class="todo-input" v-model="msg">
        <button class="add" @click="sendMsg">发送消息</button>
      </div>
      <div class="todo-lists">
        <div v-for="(item, index) in msgLists" :key="index" :class="item.from">
            {{ item.content }}
        </div>
       
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';

const msg = ref("");
// 消息列表
const msgLists = ref([])
// 向服务端发送消息
const sendMsg = () => {
  socket.send(msg.value);
  msgLists.value.push({
    content: msg.value,
    from: 'client'
  })
}

let socket = null;
const initSocket = () => {
  socket = new WebSocket('ws://localhost:8080');
  socket.onopen = onopen;
  socket.onmessage = onmessage;
  socket.onerror = onerror;
  socket.onclose = onclose;
}
// 连接成功事件
const onopen = () => {
  console.log('连接成功了');
}
// 接收消息
const onmessage = (e) => {
  msgLists.value.push({
    content: e.data,
    from: 'server'
  })
}
// 错误事件
const onerror = (e) => {
  console.log(e);
}
// 关闭连接事件
const onclose = (e) => {
  console.log(e);
}

onMounted(() => {
  initSocket();
})
</script>

<style lang="scss" scoped>
 .todo-container{
        max-width: 600px;
        padding: 30px;
        border: 1px solid #ccc;
        border-radius: 15px;
        margin: 20px auto;
      }
      .todo-header{
        height: 80px;
        display: flex;
        align-items: center;
        
      }
      .todo-input{
        flex: 1;
        height: 60px;
        border-radius:10px;
      }
      .todo-lists{
        margin-top: 30px;
      }
      .todo-item{
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #333;
      }
      .client{
        line-height: 30px;
        text-align: right;
        color: rgb(214, 103, 43);
      }
     .server{
        line-height: 30px;
        text-align: left;
        color: #beb9b9;
      }
</style>